package com.ldg.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ld.utils.PageUtils;
import com.ld.utils.Query;

import com.ldg.shop.dao.GoodsDao;
import com.ldg.shop.dao.GoodsDescDao;
import com.ldg.shop.dao.ItemDao;
import com.ldg.shop.entity.GoodsDescEntity;
import com.ldg.shop.entity.GoodsEntity;
import com.ldg.shop.entity.ItemEntity;
import com.ldg.shop.group.Goods;
import com.ldg.shop.service.GoodsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


@Service("goodsService")
@Transactional
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, GoodsEntity> implements GoodsService {

    @Resource
    private GoodsDao goodsDao;
    @Resource
    private GoodsDescDao goodsDescDao;
    @Resource
    private ItemDao itemDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GoodsEntity> page = this.page(
                new Query<GoodsEntity>().getPage(params),
                new QueryWrapper<GoodsEntity>().orderBy(true,true,"audit_status")
        );

        return new PageUtils(page);
    }

    /**
     * 保存商品相关
     * @param goods
     */
    @Override
    public void save(Goods goods) {
        //goods表添加
        baseMapper.insert(goods.getGoods());
        //goodsdesc表添加
        //设置外键
        goods.getGoodsDesc().setGoodsId(goods.getGoods().getId());
        goodsDescDao.insert(goods.getGoodsDesc());
        //item表添加
        for (ItemEntity item : goods.getItems()) {
            //设置外键
            item.setGoodsId(goods.getGoods().getId());
            item.setCategoryid(goods.getGoods().getCategory3Id());
            itemDao.insert(item);
        }
    }

    @Override
    public void updateById(Goods goods) {
        //修改spu商品表
        baseMapper.updateById(goods.getGoods());
        //修改sup商品描述表
        goodsDescDao.updateById(goods.getGoodsDesc());
        //先根据goodsId从sku商品表中删除所有信息，再添加新的商品描述信息
        itemDao.delete(new QueryWrapper<ItemEntity>().eq("goods_id",goods.getGoods().getId()));
        for (ItemEntity item : goods.getItems()) {
            //将spu商品id与sku商品进行绑定
            item.setGoodsId(goods.getGoods().getId());
            //添加到数据库中
            itemDao.insert(item);
        }
    }

    @Override
    public Goods FindById(String id) {
        //把goods需要的数据都查出来
        GoodsEntity goodsEntity = baseMapper.selectById(id);
        GoodsDescEntity goodsDescEntity = goodsDescDao.selectById(id);
        List<ItemEntity> itemEntities = itemDao.selectList(new QueryWrapper<ItemEntity>().eq("goods_id", id));
        //返回goods
        return new Goods(goodsEntity,goodsDescEntity,itemEntities);
    }

}
